import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent, SimpleTableButton } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { NzTreeNode, NzModalService, NzMessageService, NzFormatEmitEvent } from 'ng-zorro-antd';
import { BaseController } from '@shared/base-controller';
import { FormBuilder } from '@angular/forms';
import { Constant } from '@core/constant';
import { UserService } from '../../../service/user/user.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ClientEditComponent } from './edit/edit.component';
import { Client } from '../../../service/auth/auth.service';

@Component({
  selector: 'admin-client-list',
  templateUrl: './client-list.component.html'
})
export class AdminClientListComponent extends BaseController implements OnInit {
  
  // 分类节点集合
  nodes = [];    
  // 当前被选中的节点
  currentNode: NzTreeNode = null;
  searchValue

  ps = 10;
  q: any = {
    parentId: "-1",
    name: ""
  };
  url = this.userService.secondList();
  data = [];
  @ViewChild('st') st: SimpleTableComponent;
  defaultSelectKeys = [];

  columns: SimpleTableColumn[] = [           
      { title: '账号', index: 'childUserName', i18n: 'account'},            
      { title: '名称', index: 'childName', i18n: 'name' },
      { title: '联系人', index: 'link_man', i18n: 'contact' },
      { title: '电话', index: 'tel', i18n: 'tel' },
      { title: 'Email', index: 'email', i18n: 'email' },    
      { title: '状态', index: 'is_disabled', i18n: 'status', render: 'isDisabled' },    
      {      
        title: '',
        buttons: [        
          { 
            text: '编辑',
            i18n: 'edit',
            type: 'modal',
            component: ClientEditComponent,
            paramName: 'record',            
            size: 600,      
            modal: {modalOptions: {nzStyle: {'top': '24px'}}},   
            click: (record: any, modal: any) => this.st.reload()
          },
          {
            text: '禁用',
            i18n: 'disable',
            pop: true,
            popTitle: 'Account disable?',                    
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return item.is_disabled === '0';
            },
            click: (record: any) => this.disable(record.child_id)
          },
          {
            text: '解禁', 
            i18n: 'enable',   
            pop: true,
            popTitle: 'Account enable?',                   
            iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              return item.is_disabled === '1';
            },
            click: (record: any) =>this.enable(record.child_id)
          }
        ]
      }    
  ];

  constructor(
    private modalService: NzModalService,
    public msg: NzMessageService, 
    private modalSrv: ModalHelper,        
    private fb: FormBuilder,
    private userService: UserService,  
    public injector: Injector ,
    private cnt: Constant
  ) {
    super(injector);
  }

  ngOnInit() {
    this.loadTree();
  }


  loadTree() {
    this.userService.agentTree().pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(list => {            
        this.nodes = [];
        let o = this.replaceKeysDeep(list, this.mapShortToLong);            
        for (let index = 0; index < o.length; index++) {
            this.nodes.push(
                new NzTreeNode(o[index])
            );
        }   
        if (o.length === 1) {
          this.defaultSelectKeys = o[0].key;
          this.currentNode = this.nodes[0];           
          this.q.parentId = this.nodes[0].key;
          this.st.load(1, this.q);  
        }
    })
  }

  mapShortToLong: any = {
      "id": "key",
      "label": "title"
  };

  mouseAction(name: string, e: NzFormatEmitEvent): void { 
    if (name === 'click') {            
      if (e.node.isSelected) {            
        this.currentNode = e.node;           
        this.q.parentId = e.node.key;
        this.st.load(1, this.q);          
      } else {
          this.currentNode = null;
          this.q.parentId = "-1";
          this.st._data = [];             
      }
    }   
  }

  addClient() {
    if (!this.currentNode) {
      this.msg.warning("Please select one 1nd customer");
      return;
    }
    this.modalSrv.static(ClientEditComponent, {parentId: this.currentNode.key}, 600, {nzStyle: {'top': '24px'}}).subscribe((e) => {
        this.st.load(1, this.q);            
    });

  }

  enable(id) {
    this.userService.enable(id).pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success('Successful');
            this.st.load(1, this.q);         
        } else {
            this.msg.error(ret.message);
        }
    });
  }

  disable(id) {
    this.userService.disable(id).pipe(
        catchError(err => {                             
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success('Successful');
            this.st.load(1, this.q);         
        } else {
            this.msg.error(ret.message);
        }
    });
  }

}
